package com.trt.contentcenter.controller.content;

import com.github.pagehelper.PageInfo;
import com.sun.org.apache.regexp.internal.RE;
import com.trt.contentcenter.auth.CheckLogin;
import com.trt.contentcenter.domain.dto.content.ShareDTO;
import com.trt.contentcenter.domain.entity.content.Share;
import com.trt.contentcenter.service.content.ShareService;
import com.trt.contentcenter.util.JwtOperator;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-03-21 04:23
 */
/**
 * Feign传递Token
 * 1.@RequestHeader
 * 2.RequestInterceptor
 *
 * RestTemplate传递Token
 * 1.exchange()
 * 2.ClientHttpRequestInterceptor
 *
 */
@RestController
@RequestMapping("/shares")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareController {

    private final ShareService shareService;

    private final JwtOperator jwtOperator;

//    @GetMapping("/{id}")
//    @CheckLogin
//    public ShareDTO findById(@PathVariable Integer id,
//                             @RequestHeader("X-Token") String token){
//        return this.shareService.findById(id, token);
//    }

    @GetMapping("/{id}")
    @CheckLogin
    public ShareDTO findById(@PathVariable Integer id){
        return this.shareService.findById(id);
    }

    /**
     * 分享列表页
     * @param title
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/q")
    public PageInfo<Share> q(@RequestParam(required = false) String title,
                             @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                             @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                             @RequestHeader(value = "X-Token", required = false) String token){
        // 注意点: pageSize无比做控制,10000
        if (pageSize > 100) {
            pageSize = 100;
        }
        Integer userId = null;
        if (StringUtils.isNotBlank(token)) {
            Claims claims = this.jwtOperator.getClaimsFromToken("token");
            userId = (Integer)claims.get("id");
        }
        return this.shareService.q(title, pageNo, pageSize, userId);
    }

    /**
     * 积分兑换指定分享
     * @param id
     * @return
     */
    @GetMapping("/exchange/{id}")
    @CheckLogin
    public Share exchangeById(@PathVariable Integer id, HttpServletRequest request){
        return this.shareService.exchangeById(id, request);
    }


}